package com.albon.soccer;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;

import com.albon.sportsalarm.R;
import com.albon.util.Logg;

import net.htmlparser.jericho.Element;
import net.htmlparser.jericho.HTMLElementName;
import net.htmlparser.jericho.Source;
import android.app.ProgressDialog;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Handler;



public class SoccerParser
{
	private final String TAG = "SoccerParser";
	private String soccer_host;
	private String soccer_link;
	private Context context;
	private Handler handler;
	private Source source;
	
	private String year;
	private String month;
	private String league;
	private ProgressDialog pDialog = null;
	
	private ArrayList<HashMap<String, String>> data;
	private int world = 0;
	private String mYear;
	private String mMonth;
	private  String[] notification_time_array_name =  {};
	public SoccerParser(Context context, Handler handler, ArrayList<HashMap<String, String>> data, int world, String mYear, String mMonth, String league)
	{
		this.context = context;
		this.handler = handler;
		this.data = data;
		this.world = world;
		this.mYear = mYear;		
		this.mMonth = mMonth;
		this.league = league;
		notification_time_array_name = context.getResources().getStringArray(R.array.notification_time_array_name);
	}
	
	public void parser() {
		year = mYear;
		month = mMonth;
		league = league;
		
		soccer_host = "http://sports.media.daum.net";
		if(world==0){ // 해외 축구
			soccer_link = "/worldsoccer/all/schedule/main.daum?game_year=" 
						+ year
						+ "&game_month="
						+ month
						+ "&league="
						+ league
						+ "&team_id=&sort=";
		}else{        // 국내 축구
			soccer_link = "/soccer/k_league/schedule/main.daum?game_year=" 
						+ year
						+ "&game_month="
						+ month;
			
		}
		//Logg.d(TAG, "soccer_link : "+soccer_link);
		try {
			process();
		} catch(IOException e){
			e.printStackTrace();
		}
	}
	
	public void progressStatus(int total) {
		pDialog.setProgress(total);
	}
	
	private void process() throws IOException {

		new Thread() {
			@Override
			public void run() {
				// TODO Auto-generated method stub
				URL nURL;
				try {
					nURL = new URL(soccer_host + soccer_link);
					
					handler.post(new Runnable() {

						@Override
						public void run() {
							// TODO Auto-generated method stub
							pDialog = ProgressDialog.show(context, "", "로딩중");
							pDialog.setCancelable(true);
						}
					});
					
					data.clear();
					
					/***********************
					 * Jericho HTML Parser
					 * ********************/
					InputStream html = nURL.openStream();
					source = new Source(new InputStreamReader(html, "utf-8"));
					
					Element table = (Element)source.getAllElements(HTMLElementName.TABLE).get(0);
					int tr_count = table.getAllElements(HTMLElementName.TR).size();
					Element tr = null;
					
					HashMap<String, String> hashmap = null;
					
					for(int i=1; i<tr_count; i++) {
						tr = (Element) table.getAllElements(HTMLElementName.TR).get(i);
						int td_count = tr.getAllElements(HTMLElementName.TD).size();
						//Logg.d(TAG, "td_count : "+td_count);
						String real_date	= "";
						String real_time	= "";
						String stadium      = "";
						String compare_date = ""; //db와 날짜 비교
						String a_team		= "";
						String b_team		= "";
						String score		= "";
						
						hashmap = new HashMap<String, String>();
						/*
						 * 경기가 끝난경우만 불러오자*/
						if(td_count == 8) { //해외축구
							String date = ((Element)tr.getAllElements(HTMLElementName.TD).get(0)).getContent().toString();
							String team1 = ((Element)tr.getAllElements(HTMLElementName.TD).get(1)).getContent().toString();
							String vs = ((Element)tr.getAllElements(HTMLElementName.TD).get(2)).getContent().toString();
							String team2 = ((Element)tr.getAllElements(HTMLElementName.TD).get(3)).getContent().toString();
							String time = ((Element)tr.getAllElements(HTMLElementName.TD).get(4)).getContent().toString();
							String relay = ((Element)tr.getAllElements(HTMLElementName.TD).get(5)).getContent().toString();
							String l_stadium = ((Element)tr.getAllElements(HTMLElementName.TD).get(6)).getContent().toString();
							String league = ((Element)tr.getAllElements(HTMLElementName.TD).get(7)).getContent().toString();
							
							/*
							 * 의미있는 데이터를 만들자*/
							//Log.d(TAG, "date : "+date);
							//Logg.d(TAG, "date : "+date.substring(0, date.lastIndexOf("일 ")));
							compare_date = mYear+mMonth+date.substring(0, date.lastIndexOf("일 "));
							//Logg.d(TAG, "compare_date : "+compare_date);
							real_date = month + "월 " + date.replaceAll(" ", "");
							real_time = time.substring(0, 5);
							
							int team1_open_em_tag = team1.indexOf("<em>");
							int team1_close_em_tag = team1.indexOf("</em>");
							a_team = team1.substring(0, team1_open_em_tag);
							
							String a_team_score = "";
							a_team_score = team1.substring(team1_open_em_tag + 4, team1_close_em_tag);
							
							int team2_open_em_tag = team2.indexOf("<em>");
							int team2_close_em_tag = team2.indexOf("</em>");
							//team2.contains("<img src=");
							//Logg.d(TAG, "team2 : "+team2.contains("<img src="));
							String b_team_score = "";
							b_team_score = team2.substring(team2_open_em_tag + 4, team2_close_em_tag);
							
							if(team2.contains("<img src=")==true){
								b_team = team2.substring(team2_close_em_tag + 6, team2.indexOf("<img src="));
								score = "경기 취소";
							}else{
								b_team = team2.substring(team2_close_em_tag + 6, team2.length());
								score = a_team_score + ":" + b_team_score;
							}
							
							
							hashmap.put("real_date",	real_date);
							hashmap.put("real_time",	real_time);
							hashmap.put("stadium",	    l_stadium);
							hashmap.put("compare_date",	compare_date);
							hashmap.put("a_team",		a_team.trim());
							hashmap.put("b_team",		b_team.trim());
							hashmap.put("enable",		"false");    //알람 on/off
							hashmap.put("notification",		context.getResources().getText(R.string.match_finished).toString()); // 알람 몇시간전 알림 
							hashmap.put("score",		score);
						}
						
						/*
						 * 경기가 예정되어 있는 경우를 불러오자*/
						else if(td_count == 6){  //해외 축구
							String date = ((Element)tr.getAllElements(HTMLElementName.TD).get(0)).getContent().toString();
							String team = ((Element)tr.getAllElements(HTMLElementName.TD).get(1)).getContent().toString();
							String time = ((Element)tr.getAllElements(HTMLElementName.TD).get(2)).getContent().toString();
							String relay = ((Element)tr.getAllElements(HTMLElementName.TD).get(3)).getContent().toString();
							String l_stadium = ((Element)tr.getAllElements(HTMLElementName.TD).get(4)).getContent().toString();
							String league = ((Element)tr.getAllElements(HTMLElementName.TD).get(5)).getContent().toString();
							
							/*
							 * 의미있는 데이터를 만들자
							 * */
							
							//Log.d(TAG, "date : "+date);
							//Logg.d(TAG, "date : "+date.substring(0, date.lastIndexOf("일 ")));
							compare_date = mYear+mMonth+date.substring(0, date.lastIndexOf("일 "));
							//Logg.d(TAG, "compare_date : "+compare_date);
							real_date = month + "월 " + date.replaceAll(" ", "");
							
							if(time.length()==0)
								real_time = "";
							else
								real_time = time.substring(0, 5);
							
							if(team.contains("vs") == true) {
								int team_vs_char = team.indexOf("vs");
								int team_img_tag = team.indexOf("<img src=");
								a_team = team.substring(0, team_vs_char);
								
								if(team.contains("<img src=")==true) {
									b_team = team.substring(team_vs_char+3, team_img_tag-1);
									score = "경기 취소";
								} else {
									b_team = team.substring(team_vs_char+3, team.length());
								}
								
							} else {
								a_team = "";
								b_team = "";
							}
							
//							System.out.println(real_date+" "+real_time+" "+a_team+" "+score+" "+b_team);
							
							if(a_team.length()!=0 && b_team.length()!=0 && time.length()!=0) {
								hashmap.put("real_date",	real_date);
								hashmap.put("real_time",	real_time);
								hashmap.put("stadium",	    l_stadium);
								hashmap.put("compare_date",	compare_date);
								hashmap.put("a_team",		a_team.trim());
								hashmap.put("b_team",		b_team.trim());
								Soccer soccer = call_alarm_values(compare_date, a_team.trim(), b_team.trim()); 
								if(soccer!=null){
									hashmap.put("enable",		soccer.getEnable());
									int notification = Integer.parseInt(soccer.getNotification());
									hashmap.put("notification",		notification_time_array_name[notification]);
									
								}else{
									hashmap.put("enable",		"false");
									hashmap.put("notification",		notification_time_array_name[0]);
								}								
								hashmap.put("score",		score);
							}
						}
						else if(td_count == 9){ // k 리그 이미 종료된 경기
							String date = ((Element)tr.getAllElements(HTMLElementName.TD).get(0)).getContent().toString();
							String team1 = ((Element)tr.getAllElements(HTMLElementName.TD).get(1)).getContent().toString();
							String vs = ((Element)tr.getAllElements(HTMLElementName.TD).get(2)).getContent().toString();
							String team2 = ((Element)tr.getAllElements(HTMLElementName.TD).get(3)).getContent().toString();
							String time = ((Element)tr.getAllElements(HTMLElementName.TD).get(4)).getContent().toString();
							String relay = ((Element)tr.getAllElements(HTMLElementName.TD).get(5)).getContent().toString();
							String l_stadium = ((Element)tr.getAllElements(HTMLElementName.TD).get(6)).getContent().toString();
							String league = ((Element)tr.getAllElements(HTMLElementName.TD).get(7)).getContent().toString();
							String weather = ((Element)tr.getAllElements(HTMLElementName.TD).get(8)).getContent().toString();
							
							/*Logg.d(TAG, "date : "+date);
							Logg.d(TAG, "team1 : "+team1);
							Logg.d(TAG, "vs : "+vs);
							Logg.d(TAG, "team2 : "+team2);
							Logg.d(TAG, "time : "+time);
							Logg.d(TAG, "relay : "+relay);
							Logg.d(TAG, "stadium : "+stadium);
							Logg.d(TAG, "league : "+league);*/
							
							
							compare_date = mYear+mMonth+date.substring(0, date.lastIndexOf("일 "));
							
							real_date = month + "월 " + date.replaceAll(" ", "");
							real_time = time.substring(0, 5);
							
							int team1_open_em_tag = team1.indexOf("<em>");
							int team1_close_em_tag = team1.indexOf("</em>");
							a_team = team1.substring(0, team1_open_em_tag);
							
							String a_team_score = "";
							a_team_score = team1.substring(team1_open_em_tag + 4, team1_close_em_tag);
							
							int team2_open_em_tag = team2.indexOf("<em>");
							int team2_close_em_tag = team2.indexOf("</em>");
							b_team = team2.substring(team2_close_em_tag + 6, team2.length());
							
							String b_team_score = "";
							b_team_score = team2.substring(team2_open_em_tag + 4, team2_close_em_tag);
														
							
							if(team2.contains("<img src=")==true){
								b_team = team2.substring(team2_close_em_tag + 6, team2.indexOf("<img src="));
								score = "경기 취소";
							}else{
								b_team = team2.substring(team2_close_em_tag + 6, team2.length());
								score = a_team_score + ":" + b_team_score;
							}
							
							hashmap.put("real_date",	real_date);
							hashmap.put("real_time",	real_time);
							hashmap.put("stadium",	    l_stadium);
							hashmap.put("compare_date",	compare_date);
							hashmap.put("a_team",		a_team.trim());
							hashmap.put("b_team",		b_team.trim());
							hashmap.put("enable",		"false");    //알람 on/off
							hashmap.put("notification",	context.getResources().getText(R.string.match_finished).toString()); // 알람 몇시간전 알림 
							hashmap.put("score",		score);
						}
						else if(td_count == 7){  //k 리그 아직 시작안한경기
							String no_match = ((Element)tr.getAllElements(HTMLElementName.TD).get(1)).getContent().toString();
							//Logg.d(TAG, "no_match.substring(0, 2) : "+no_match.substring(0, 2));
							if(!no_match.substring(0, 2).equals("경기")){
								String date = ((Element)tr.getAllElements(HTMLElementName.TD).get(0)).getContent().toString();
								String team = ((Element)tr.getAllElements(HTMLElementName.TD).get(1)).getContent().toString();
								String team1 = team.substring(0, team.indexOf(" vs"));
								String team2 = team.substring(team.indexOf("vs ")+3);
								
								String time = ((Element)tr.getAllElements(HTMLElementName.TD).get(2)).getContent().toString();
								String relay = ((Element)tr.getAllElements(HTMLElementName.TD).get(3)).getContent().toString();
								String l_stadium = ((Element)tr.getAllElements(HTMLElementName.TD).get(4)).getContent().toString();
								String league = ((Element)tr.getAllElements(HTMLElementName.TD).get(5)).getContent().toString();
								String weather = ((Element)tr.getAllElements(HTMLElementName.TD).get(6)).getContent().toString();
							
								
								
								compare_date = mYear+mMonth+date.substring(0, date.lastIndexOf("일 "));
								
								real_date = month + "월 " + date.replaceAll(" ", "");
								real_time =time;
								a_team = team1;	
								
								if(team2.contains("<img src=")==true){
									b_team = team2.substring(0, team2.indexOf("<img src="));
									score = "경기 취소";
								}else{
									b_team = team2;
									
								}
								hashmap.put("real_date",	real_date);
								hashmap.put("real_time",	real_time.trim());
								hashmap.put("stadium",	    l_stadium);
								hashmap.put("compare_date",	compare_date);
								hashmap.put("a_team",		a_team.trim());
								hashmap.put("b_team",		b_team.trim());
								Soccer soccer = call_alarm_values(compare_date, a_team.trim(), b_team.trim()); 
								if(soccer!=null){
									hashmap.put("enable",		soccer.getEnable());
									int notification = Integer.parseInt(soccer.getNotification());
									hashmap.put("notification",		notification_time_array_name[notification]);
									
								}else{
									hashmap.put("enable",		"false");
									hashmap.put("notification",		notification_time_array_name[0]);
								}								
								hashmap.put("score",		score);
							}
						
						}
						
						data.add(hashmap);
					}

					handler.post(new Runnable() {
						@Override
						public void run() {
							// TODO Auto-generated method stub
							//Logg.d(TAG, "==끝==");
							pDialog.dismiss();
							
							handler.sendEmptyMessage(0);
						}
					});
				} catch(MalformedURLException e) {
					e.printStackTrace();
				} catch(Exception e) {
					e.printStackTrace();
				}
			}
			
		}.start();
	}
	
	private Soccer call_alarm_values(String key_compare_date, String key_a_team, String key_b_team){
    	Soccer soccer = null;
    	SQLiteDatabase databse = null;		
		if(databse == null){
			databse = context.openOrCreateDatabase(DatabaseHelper.DATABASE_NAME, SQLiteDatabase.CREATE_IF_NECESSARY, null);
		}
		String stringWhere = " WHERE " + DatabaseHelper.DATABASE_COLUMN_COMPARE_DATE + " = '" +key_compare_date+"' and "+ DatabaseHelper.DATABASE_COLUMN_A_TEAM +" = '"+key_a_team+"' and "+DatabaseHelper.DATABASE_COLUMN_B_TEAM+" = "+"'"+key_b_team+"'";		
		
		Cursor cursor = null;

		try {
			cursor = databse.rawQuery("SELECT "
					+ DatabaseHelper.DATABASE_COLUMN_ID + ", "
					+ DatabaseHelper.DATABASE_COLUMN_ENABLED + ", "
					+ DatabaseHelper.DATABASE_COLUMN_REAL_DATE + ", "
					+ DatabaseHelper.DATABASE_COLUMN_REAL_TIME + ", "
					+ DatabaseHelper.DATABASE_COLUMN_COMPARE_DATE + ", "
					+ DatabaseHelper.DATABASE_COLUMN_SETTING_YEAR + ", "
					+ DatabaseHelper.DATABASE_COLUMN_SETTING_MONTH + ", "
					+ DatabaseHelper.DATABASE_COLUMN_REAGUE + ", "
					+ DatabaseHelper.DATABASE_COLUMN_STADIUM + ", "
					+ DatabaseHelper.DATABASE_COLUMN_A_TEAM + ", "
					+ DatabaseHelper.DATABASE_COLUMN_B_TEAM + ", "
					+ DatabaseHelper.DATABASE_COLUMN_SCORE + ", "
					+ DatabaseHelper.DATABASE_COLUMN_ALARM_TITLE + ", "
					+ DatabaseHelper.DATABASE_COLUMN_ALARM_RINGTONE + ", "
					+ DatabaseHelper.DATABASE_COLUMN_ALARM_VOLUME + ", "
					+ DatabaseHelper.DATABASE_COLUMN_ALARM_VIBRATE + ", "
					+ DatabaseHelper.DATABASE_COLUMN_ALARM_AUTO_OFF_TIME + ", "
					+ DatabaseHelper.DATABASE_COLUMN_SMS + ", "
					+ DatabaseHelper.DATABASE_COLUMN_VIDEO + ", "
					+ DatabaseHelper.DATABASE_COLUMN_RECORD + ", "						
					+ DatabaseHelper.DATABASE_COLUMN_HIGHLIGHT + ", "						
					+ DatabaseHelper.DATABASE_COLUMN_POWER + ", "													
					+ DatabaseHelper.DATABASE_COLUMN_NOTIFICATION + ", "													
					+ DatabaseHelper.DATABASE_COLUMN_EXPLANATION + " " + " FROM "
					+ DatabaseHelper.DATABASE_TABLE_NAME + " " + stringWhere, null);
			if (cursor != null && cursor.moveToFirst()) {
				do {
					
					soccer = new Soccer(cursor.getInt(0), cursor.getString(1), cursor.getString(2), cursor.getString(3), cursor.getString(4), cursor.getString(5), cursor.getString(6), cursor.getString(7), cursor.getString(8), cursor.getString(9), cursor.getString(10), cursor.getString(11), cursor.getString(12), cursor.getString(13), cursor.getString(14), cursor.getString(15), cursor.getString(16), cursor.getString(17), cursor.getString(18), cursor.getString(19), cursor.getString(20), cursor.getString(21), cursor.getString(22), cursor.getString(23));
					
				} while (cursor.moveToNext());
			}		
					
								
		} finally {
			if (cursor != null)
				cursor.close();
			if(databse != null){
				databse.close();
			}
		}
		return soccer;
    }
}
